package cn.hello2018.listener;

import java.util.ArrayList;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import cn.hello2018.entity.User;
import cn.hello2018.util.SessionUtil;

@WebListener
public class MyHttpSessionListener implements HttpSessionListener {
	
	private int userNumber = 0;

	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		++userNumber;
		arg0.getSession().getServletContext().setAttribute("userNumber", userNumber);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		--userNumber;
		arg0.getSession().getServletContext().setAttribute("userNumber", userNumber);
		
		ArrayList<User> userList = null;
		userList = (ArrayList<User>) arg0.getSession().getServletContext().getAttribute("userList");
		Object sessionId = SessionUtil.getUserBySessionId(userList, arg0.getSession().getId());
		if(sessionId != null) {
			userList.remove(sessionId);
		}
	}

}
